<template>
  <h1>微博首页</h1>

  <div v-if="user==null">
    <router-link to="/reg">注册</router-link> |
    <router-link to="/login">登录</router-link>
  </div>
  <div v-else>
    <h2>欢迎{{user.nickname}}回来!</h2>
    <router-link to="/post">发微博</router-link>
    <el-button @click="logout()">退出登录</el-button>
  </div>
  <hr>
  <div v-for="weibo in arr">
    <router-link :to="'/detail?id='+weibo.id">
      <h3>{{weibo.nickname}}说:{{weibo.content}}</h3>
    </router-link>
    <p>{{weibo.imgUrl}}</p>
<!--  http://localhost:8080/2023/12/16/xxx.jpg  -->
    <img :src="'http://localhost:8080'+weibo.imgUrl" width="200">

  </div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";

const arr = ref([]);
//所有进入页面就发请求的带写在此声明周期方法中
onMounted(()=>{
  axios.get('http://localhost:8080/v1/weibos').then((response)=>{
    if (response.data.code==2001){
      //把服务器响应回来的微博数据装进数组中
      arr.value = response.data.data;
    }
  })
})

const logout = ()=>{
  if (confirm("您确认退出登录吗?")){
    localStorage.clear();
    user.value=null;
  }
}
//从LocalStorage中获取用户数据如果有,需要将JSON格式字符串转成JS对象,没有则为null
let user = ref(localStorage.user?JSON.parse(localStorage.user):null);

</script>
